package com.elinshaw.pattern.future;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Administrator
 */
public class FutureServiceImpl<IN, OUT> implements FutureService<IN, OUT> {

    private final AtomicInteger nextCounter = new AtomicInteger(0);

    @Override
    public Future<?> submit(Runnable runnable) {
        final FutureTask<Void> future = new FutureTask<>();
        new Thread(() -> {
            runnable.run();
            future.finish(null);
        }, "线程名" + nextCounter.getAndIncrement()).start();
        return future;
    }

    @Override
    public Future<OUT> submit(Task<IN, OUT> task, IN input) {
        final FutureTask<OUT> future = new FutureTask<>();
        new Thread(() -> {
            OUT result = task.get(input);
            future.finish(result);

        }, "线程名" + nextCounter.getAndIncrement()).start();
        return future;
    }

    @Override
    public Future<OUT> submit(Task<IN, OUT> task, IN input, Callback<OUT> callback) {
        final FutureTask<OUT> future = new FutureTask<>();
        new Thread(() -> {
            OUT result = task.get(input);
            future.finish(result);
            if (callback != null) {
                callback.call(result);
            }
        }, "线程名" + nextCounter.getAndIncrement()).start();
        return future;
    }

}
